/**
 * 2018.6.13 批量生成二维码压缩包
 *  Qrcode [function] 生成二维码构造函数
 *  transImg [function] @item 内容 @index 索引 @length 数组总长度  @options 二维码配置 @callbacks 各种状态回调集合
 *  gzip [function] @zip 要压缩的zip对象
 *  myreadFile [function] @filePath 根据系统路径读取文件
 *  author [hu youming]
 *  npm i
 *  npm run gzip filepath/filename
 */

var fs = require('fs');
var qr = require('qr-image');
var JSZip = require("jszip");
var zip = new JSZip();

//生成二维码
const Qrcode = function (options) {
    let defaultOptions = {
        type: 'png',
        size: 5
    };
    this.options = { ...defaultOptions, ...options };
}
Qrcode.prototype = {
    zipPath: '', // 压缩包存放路径
    zipName: '', // 压缩包名字
    callbacks: {}, // 回调函数集合
    generate: function (filepath, funcs) {
        var arr = filepath.split('\\');
        var fileArr = arr[arr.length - 1].split('.');
        this.zipPath = arr.slice(0, arr.length - 1).join('\\');
        this.zipName = fileArr.slice(0, fileArr.length - 1).join('.');
        this.callbacks = funcs;
        this.myreadFile(filepath);
    },
    transImg: function (item, index, length, done) {
        try {
            if (!!item) {
                var qr_img = qr.imageSync(item, this.options);
                zip.file(`台卡编号[${item}].png`, qr_img);
            }
            if (length - 1 == index) { // 完成
                done(zip)
            } else {
                this.callbacks.padding && this.callbacks.padding({
                    currentIndex: index,
                    total: length
                })
            }
        } catch (err) {
            this.callbacks.error && this.callbacks.error(err)
        }
    },
    gzip: function (zip, total) {
        var path = this.zipPath;
        var name = this.zipName;
        var that = this;
        zip
            .generateNodeStream({ type: 'nodebuffer', streamFiles: true })
            .pipe(fs.createWriteStream(`${path}/${name}.zip`))
            .on('finish', function () {
                that.callbacks.success && that.callbacks.success({
                    msg: '生成完成',
                    total: total
                })
            });
    },
    myreadFile: function (filePath) {
        let that = this;
        fs.readFile(filePath, function (err, data) {
            if (err) {
                return console.error(err);
            }
            var temparr = data.toString().split('\n'), arr = [];
            for (var k = 0; k < temparr.length; k++) { // 过滤空值
                temparr[k] = temparr[k].replace(/"|\r/g, '');
                if (!!temparr[k]) {
                    arr.push(temparr[k])
                }
            }
            var arrLength = arr.length;
            for (var i = 0; i < arrLength; i++) {
                that.transImg(arr[i], i, arrLength, function (zip) {
                    that.gzip(zip, arrLength);
                })
            }
        });
    }
}
module.exports = Qrcode

